using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.ShelfDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.ShelfDictionaryHandler
{
    /// <summary>
    /// 创建货架处理器
    /// </summary>
    public class CreateShelvesHandler : IRequestHandler<CreateShelvesCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Shelves> _shelvesRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        public CreateShelvesHandler(IBaseRepository<Shelves> shelvesRepository, IMapper mapper)
        {
            _shelvesRepository = shelvesRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理创建货架请求
        /// </summary>
        public Task<ApiResult<int>> Handle(CreateShelvesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var shelves = _mapper.Map<Shelves>(request.ShelvesData);

                // 自动生成货架条码：BC+4位随机数字
                var random = new Random();
                shelves.Barcode = $"BC{random.Next(1000, 9999)}";

                // 设置默认状态为启用(1)
                shelves.Status = 1;

                var result = _shelvesRepository.Create(shelves);

                return Task.FromResult(new ApiResult<int>
                {
                    Code = result > 0 ? ApiEnums.Success : ApiEnums.Fail,
                    Msg = result > 0 ? "创建货架成功" : "创建货架失败",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new ApiResult<int>
                {
                    Code = ApiEnums.Error,
                    Msg = $"创建货架发生异常：{ex.Message}",
                    Data = 0
                });
            }
        }
    }
}